package com.talking.view;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.talking.App;
import com.talking.databinding.ActivityForgotPasswordBinding;
import com.talking.presenter.UserPresenter;
import com.talking.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ForgotPasswordActivity extends AppCompatActivity {
    private ActivityForgotPasswordBinding binding;
    private String yzm;
    int time=40;
    Handler handle = new Handler();
    Runnable runnable = new Runnable() {
        @SuppressLint("SetTextI18n")
        @Override
        public void run() {
            time--;
            if (time<=0){
                binding.forgotSent.setText("发送验证码");
                binding.forgotSent.setEnabled(true);
                time=40;
            }else {
                binding.forgotSent.setEnabled(false);
                binding.forgotSent.setText(time+"s后可发送");
                handle.postDelayed(this, 1000);
            }
        }
    };
    private String verityCode="";
    private String password="",password2="";

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= ActivityForgotPasswordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.forgotEmail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                binding.forgotSent.setEnabled(Utils.isEmail(s.toString()));
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        binding.forgotVerityCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                verityCode=s.toString();
                check();
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        binding.forgotNewPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                password=s.toString();
                check();
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        binding.forgotNewPassword2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                password2=s.toString();
                check();
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        setResult(0);
    }
    private void check() {
        binding.forgotVerity.setEnabled(Utils.passwordCorrect(binding.forgotNewPassword.getText().toString())&& !password.equals("")&& !password2.equals("") && verityCode.equals(yzm));
    }
    public void sentVerityCode(View view){
        yzm=Utils.createRandom(4);
        UserPresenter.sendEmail(binding.forgotEmail.getText().toString(), yzm, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                runOnUiThread(() -> {
                    Utils.toast("已发送验证码");
                    binding.forgotSent.setEnabled(false);
                });
            }
        });
        handle.postDelayed(runnable, 0);
    }
    public void verity(View view){
        if (password.equals(password2)){
            UserPresenter.changePassword(binding.forgotEmail.getText().toString().trim(), password, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    ForgotPasswordActivity.this.runOnUiThread(() -> Utils.toast( e.toString()));
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String msg = response.body().string();
                    if (!msg.equals("用户不存在")){
                        try {
                            JSONObject jo = new JSONObject(msg);
                            @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
                            edit.putString("account",jo.getString("account"));
                            edit.putString("password",jo.getString("password"));
                            edit.putString("email",jo.getString("email"));
                            edit.putBoolean("autoLogin",true);
                            edit.apply();
                            setResult(1);
                            ForgotPasswordActivity.this.finish();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }else {
                        ForgotPasswordActivity.this.runOnUiThread(() -> Utils.toast(msg));
                    }
                }
            });
        }else{
            Utils.toast("两次密码不一致");
        }

    }
    public void back(View view){ finish(); }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        handle.removeCallbacks(runnable);
    }
}